package com.jhs.kjs.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class FileDownloadViewHandler extends AbstractView{
	public FileDownloadViewHandler() {
		setContentType("application/octet-stream");
	}
	
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest req, HttpServletResponse res) throws Exception{
		File file = (File) model.get("downloadFile");
		
		res.setContentType(getContentType());
		res.setContentLength((int)file.length());
		res.setHeader("Content-Disposition", "attachment; fileName=\""+java.net.URLEncoder.encode(file.getName(), "utf-8")+"\";");
		
		res.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream out = res.getOutputStream();
		FileInputStream fis = null;
		
		try {
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException ex) {
				}
			}
		}
		out.flush();
	}
}
